package com.hk.springsecurity01.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author by 何坤
 * @Classname CaptchaController
 * @Description TODO
 * @Date 2019/11/28 17:38
 */
@RestController
@RequestMapping(value = "/captcha")
public class CaptchaController {

    @Autowired
    private Producer producer;

    @GetMapping(value = "/getCaptcha")
    public void getCaptcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("image/jpeg");
        String captchaText = producer.createText();
        // 将验证码文本设置到session
        req.getSession().setAttribute("captcha", captchaText);
        // 创建验证码图片
        BufferedImage image = producer.createImage(captchaText);
        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    }
}
